﻿#include "DeviceRegisterCodec.h"

#include "Mapper_Device.h"
#include "DataPackage_UdpCodec.h"
#include "Device.h"

#include "DeviceRegisterCodec_Unregister.h"
#include "DeviceRegisterCodec_Register.h"


DeviceRegisterCodec::DeviceRegisterCodec()
{
  setObjectName(getClassNameFirstLow<DeviceRegisterCodec>());
  codecMap.insert(Unregister,new DeviceRegisterCodec_Unregister());
  codecMap.insert(Register,new DeviceRegisterCodec_Register());
}

DeviceRegisterCodec::~DeviceRegisterCodec()
{
  for(unsigned char key:codecMap.keys())
    {
      delete codecMap.take(key);
    }
}

DataPackage_UdpCodec *DeviceRegisterCodec::decode(DataPackage_UdpCodec *dataPackageInfo_Device)
{
  if(mapper_Device->isVaildDevice(dataPackageInfo_Device->getDeviceId()))//通过设备ID检查数据包合法性
    {
      QByteArray data=dataPackageInfo_Device->getData();
      if(data.size()!=1)//检查数据体合法性
        {
          return Q_NULLPTR;
        }
      return codecMap.value(data[0]&0xff)->decode(dataPackageInfo_Device);
    }
  else
    {
      return Q_NULLPTR;
    }
}

DataPackage_UdpCodec *DeviceRegisterCodec::makeAck(DataPackage_UdpCodec *dataPackageInfo_Device, RegisterType registerType)
{
  return dataPackageInfo_Device->toAck(QByteArray(registerType&0xff,1));
}

Mapper_Device* DeviceRegisterCodec::getMapper_Device() const
{
  return mapper_Device;
}

DeviceRegisterCodec* DeviceRegisterCodec::setMapper_Device(Mapper_Device * const mapper_Device)
{
  this->mapper_Device=mapper_Device;
  printInjection(this,mapper_Device);
  return this;
}

void DeviceRegisterCodec::objectAutoInjection(QHash<QString,QObject*>* objMap)
{
  setMapper_Device(getObjFromMap<Mapper_Device>(objMap));
  for(unsigned char key:codecMap.keys())
    {
      ObjAutoInject* temp=dynamic_cast<ObjAutoInject*>(codecMap.value(key));
      if(Q_NULLPTR!=temp)
        {
          temp->objectAutoInjection(objMap);
        }
    }
}
